package com.CommunityHub.kiana.controller;

import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private AdminService adminService = new AdminService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            User user = adminService.login(username, password);
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                //session.setAttribute("memberInfo", user);
                // 根据用户角色跳转到不同的首页
                String role = user.getRole();
                String redirectPage = determineHomePageByRole(role);
                response.sendRedirect(redirectPage);
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "登录失败: " + e.getMessage());
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    /**
     * 根据用户角色确定跳转的首页
     * @param role 用户角色
     * @return 对应的首页路径
     */
    private String determineHomePageByRole(String role) {
        if (role == null) {
            return "login.jsp"; // 默认返回登录页
        }

        switch (role.toLowerCase()) {
            case "admin":
                return "AdminHomeServlet";
            case "member":
                return "MemberHomeServlet";
            case "life_steward":
                return "lifeStewardHome.jsp";
            case "logistics_steward":
                return "VenueInfoListServlet";
            default:
                return "login.jsp"; // 未知角色返回登录页
        }
    }
}